package nix.jsps;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class LoginServlet extends HttpServlet {

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");

		String username = request.getParameter("username");
		String pwd = request.getParameter("pwd");
		String vcode = request.getParameter("vcode");

		String sessionVCode = (String) request.getSession().getAttribute(
				"session_vcode");

		if (!vcode.equalsIgnoreCase(sessionVCode)) {
			// 保存错误信息
			request.setAttribute("msg", "验证码错误！");
			// 转发login.jsp
			request.getRequestDispatcher("/login/login.jsp").forward(request,
					response);
			return;
		}

		if (!"abc".equalsIgnoreCase(username)) {// 登陆成功
			// 保存cookie，记住用户名
			Cookie cookie = new Cookie("uname", username);
			cookie.setMaxAge(60 * 60 * 24 * 7);
			cookie.setPath("/java-web-demo");
			response.addCookie(cookie);

			// 保存session
			HttpSession session = request.getSession();
			session.setAttribute("username", username);
			response.sendRedirect("/java-web-demo/login/succ1.jsp");

		} else {
			// 保存错误信息
			request.setAttribute("msg", "用户名或密码有误！");
			// 转发login.jsp
			request.getRequestDispatcher("/login/login.jsp").forward(request,
					response);
		}
	}

}
